package com.cn.transfer.handle.impl.purchase;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.cn.transfer.common.constant.KeyConstant;
import com.cn.transfer.common.entity.DocumentApproval;
import com.cn.transfer.common.entity.VvSaSaleOrder;
import com.cn.transfer.common.entity.VvSaSaleOrderB;
import com.cn.transfer.common.entity.jiandaoyun.JdyPurchaseOrder;
import com.cn.transfer.common.enumeration.ExceptionEnum;
import com.cn.transfer.common.http.ApiClient;
import com.cn.transfer.common.utils.ConnmeUtils;
import com.cn.transfer.common.utils.exception.BizException;
import com.cn.transfer.common.vo.MessagePushVO;
import com.cn.transfer.common.vo.PurchaseOrder;
import com.cn.transfer.common.vo.PurchaseOrderDetail;
import com.cn.transfer.handle.MessageStrategy;
import com.cn.transfer.handle.impl.purchase.community.PurchaseCommunity;
import com.cn.transfer.mapper.PuPurchaseOrderBMapper;
import com.cn.transfer.mapper.PuPurchaseOrderMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: 向伟典
 * @date: 2023/8/31 15:39
 * @Description: 采购订单审核时执行
 */
@Slf4j
@Component
public class PurchaseReviewImpl implements MessageStrategy {

    @Autowired
    private PuPurchaseOrderMapper puPurchaseOrderMapper;
    @Autowired
    private PuPurchaseOrderBMapper orderbMapper;

    @Autowired
    private PuPurchaseOrderBMapper puPurchaseOrderBMapper;


    @Override
    @Transactional
    public void handle(MessagePushVO message) {
        String jsonStr = JSONUtil.toJsonStr(message.getBizContent());
        ObjectMapper objectMapper = new ObjectMapper();
        DocumentApproval documentApproval = null;
        try {
            documentApproval = objectMapper.readValue(jsonStr, DocumentApproval.class);
        } catch (JsonProcessingException e) {
            throw new BizException("在转换BizContent集合是出现了错误，对象为");
        }
        PurchaseOrder purchaseOrder = puPurchaseOrderMapper.queryPurchaseOrders(documentApproval.getVoucherID());
        List<PurchaseOrderDetail> orderDetails = orderbMapper.getOrderDetails(purchaseOrder.getPurchaseOrderId());
        purchaseOrder.setPurchaseOrderDetails(orderDetails);
        // 查询视图，这条数据是否存在
        int i1 = puPurchaseOrderMapper.inquireIsExist(purchaseOrder.getCode());
        if (i1 == 0) {
            // 存入视图
            int i = puPurchaseOrderMapper.insertVVPuechase(purchaseOrder);
            for (PurchaseOrderDetail purchaseOrderDetail : orderDetails) {
                puPurchaseOrderBMapper.insertPurchaseOrderDetail(purchaseOrderDetail);
            }
        }
        Header[] originalHeaders = new Header[2];
        originalHeaders[0] = new BasicHeader("Authorization", "Bearer " + KeyConstant.JDY_KEY);
        originalHeaders[1] = new BasicHeader("Content-Type", "application/json;charset=utf-8");

        Map<String, Object> parameter = new HashMap<>();
        parameter.put("app_id", "64f00ef131adb70007ad6e6d");
        parameter.put("entry_id", "64f00f0e68761f0007719cf9");

        Map<String, Object> data = new HashMap<>();

        Map<String, Object> ghs = new HashMap<>();
        ghs.put("value", purchaseOrder.getPartnerName());
        data.put("ghs", ghs);

        Map<String, Object> djbh = new HashMap<>();
        djbh.put("value", purchaseOrder.getCode());
        data.put("djbh", djbh);

        Map<String, Object> yjdh = new HashMap<>();
        yjdh.put("value", purchaseOrder.getAcceptDate());
        data.put("yjdh", yjdh);

        Map<String, Object> bm = new HashMap<>();
        bm.put("value", purchaseOrder.getDepartmentName());
        data.put("bm", bm);

        Map<String, Object> ghsbm = new HashMap<>();
        ghsbm.put("value", purchaseOrder.getPartnerCode());
        data.put("ghsbm", ghsbm);

        Map<String, Object> ghsjc = new HashMap<>();
        ghsjc.put("value", purchaseOrder.getPartnerAbbName());
        data.put("ghsjc", ghsjc);

        Map<String, Object> cgy = new HashMap<>();
        cgy.put("value", purchaseOrder.getPurchaserAddress());
        data.put("cgy", cgy);

        Map<String, Object> ck = new HashMap<>();
        ck.put("value", purchaseOrder.getName());
        data.put("ck", ck);

        Map<String, Object> ddje = new HashMap<>();
        ddje.put("value", purchaseOrder.getOrigEarnestMoney());
        data.put("ddje", ddje);

        Map<String, Object> djrq = new HashMap<>();
        djrq.put("value", purchaseOrder.getVoucherdate());
        data.put("djrq", djrq);

        Map<String, Object> xsddh = new HashMap<>();
        xsddh.put("value", purchaseOrder.getSaleOrderCode());
        data.put("xsddh", xsddh);

        Map<String, Object> chdd = new HashMap<>();
        chdd.put("value", purchaseOrder.getPubuserdefnvc5());
        data.put("chdd", chdd);

        Map<String, Object> ywbm = new HashMap<>();
        ywbm.put("value", purchaseOrder.getPubuserdefnvc2());
        data.put("ywbm", ywbm);
        Map<String, Object> zdr = new HashMap<>();
        zdr.put("value", purchaseOrder.getMakerAddress());
        data.put("zdr", zdr);

        Map<String, Object> zdsj = new HashMap<>();
        zdsj.put("value", purchaseOrder.getCreateDateTime());
        data.put("zdsj", zdsj);

        Map<String, Object> shsj = new HashMap<>();
        shsj.put("value", purchaseOrder.getAuditDateTime());
        data.put("shsj", shsj);

        Map<String, Object> xsddzdr = new HashMap<>();
        xsddzdr.put("value", purchaseOrder.getSalesPersonAddress());
        data.put("xsddzdr", xsddzdr);

        Map<String, Object> xsddywy = new HashMap<>();
        xsddywy.put("value", purchaseOrder.getSalesMakerAddress());
        data.put("xsddywy", xsddywy);

        Map<String, Object> yjdhsj = new HashMap<>();
        yjdhsj.put("value", purchaseOrder.getEstimatedDateTime());
        data.put("yjdhsj", yjdhsj);

        String customerName = "";
        if (purchaseOrder.getPurchaseOrderDetails().get(0).getCustomerName() == null) {
            customerName="00";
        } else {
            customerName=purchaseOrder.getPurchaseOrderDetails().get(0).getCustomerName();
        }
        Map<String, Object> khmc = new HashMap<>();
        khmc.put("value",customerName );
        data.put("khmc", khmc);

        List<Map<String, Object>> result = new ArrayList<>();

        for (PurchaseOrderDetail detail : orderDetails) {
            Map<String, Object> detailMap = new HashMap<>();

            Map<String, Object> inventoryNameMap = new HashMap<>();
            inventoryNameMap.put("value", detail.getInventoryName());
            detailMap.put("mx_chmc", inventoryNameMap);

            Map<String, Object> productCodeMap = new HashMap<>();
            productCodeMap.put("value", detail.getProductCode());
            detailMap.put("mx_cpbm", productCodeMap);

            Map<String, Object> productNameNewMap = new HashMap<>();
            productNameNewMap.put("value", detail.getProductNameNew());
            detailMap.put("mx_cpmcx", productNameNewMap);

            Map<String, Object> specificationMap = new HashMap<>();
            specificationMap.put("value", detail.getSpecification());
            detailMap.put("mx_gzxh", specificationMap);

            Map<String, Object> specificationNewMap = new HashMap<>();
            specificationNewMap.put("value", detail.getSpecificationNew());
            detailMap.put("mx_cpggx", specificationNewMap);

            Map<String, Object> productDescriptionMap = new HashMap<>();
            productDescriptionMap.put("value", detail.getProductDescription());
            detailMap.put("mx_cpms", productDescriptionMap);

            Map<String, Object> additionalInfoNewMap = new HashMap<>();
            additionalInfoNewMap.put("value", detail.getAdditionalInfoNew());
            detailMap.put("mx_bcxxx", additionalInfoNewMap);

            Map<String, Object> additionalInfoMap = new HashMap<>();
            additionalInfoMap.put("value", detail.getAdditionalInfo());
            detailMap.put("mx_bcxx", additionalInfoMap);

            Map<String, Object> purchaserMap = new HashMap<>();
            purchaserMap.put("value", detail.getPurchaser());
            detailMap.put("mx_cgy", purchaserMap);

            Map<String, Object> quantityMap = new HashMap<>();
            quantityMap.put("value", detail.getQuantity());
            detailMap.put("mx_sl", quantityMap);

            Map<String, Object> unitNameMap = new HashMap<>();
            unitNameMap.put("value", detail.getUnitName());
            detailMap.put("mx_dj", unitNameMap);

            Map<String, Object> baseUnitPriceMap = new HashMap<>();
            baseUnitPriceMap.put("value", detail.getBaseUnitPrice());
            detailMap.put("mx_bbdj", baseUnitPriceMap);

            Map<String, Object> taxUnitPriceMap = new HashMap<>();
            taxUnitPriceMap.put("value", detail.getTaxUnitPrice());
            detailMap.put("mx_hsdj", taxUnitPriceMap);

            Map<String, Object> taxRateMap = new HashMap<>();
            taxRateMap.put("value", detail.getTaxRate());
            detailMap.put("mx_slv", taxRateMap);

            Map<String, Object> baseTaxAmountMap = new HashMap<>();
            baseTaxAmountMap.put("value", detail.getBaseTaxAmount());
            detailMap.put("mx_bbhsje", baseTaxAmountMap);

            Map<String, Object> taxAmountMap = new HashMap<>();
            taxAmountMap.put("value", detail.getTaxAmount());
            detailMap.put("mx_hsje", taxAmountMap);

            Map<String, Object> supplierCodeMap = new HashMap<>();
            supplierCodeMap.put("value", detail.getSupplierCode());
            detailMap.put("mx_gfbm", supplierCodeMap);


            Map<String, Object> customsProductNameMap = new HashMap<>();
            customsProductNameMap.put("value", detail.getCustomsProductName());
            detailMap.put("mx_bgpm", customsProductNameMap);

            Map<String, Object> productRequirementsMap = new HashMap<>();
            productRequirementsMap.put("value", detail.getProductRequirements());
            detailMap.put("mx_cpyq", productRequirementsMap);

            Map<String, Object> packagingRequirementsMap = new HashMap<>();
            packagingRequirementsMap.put("value", detail.getPackagingRequirements());
            detailMap.put("mx_bzyq", packagingRequirementsMap);

            Map<String, Object> isGiftMap = new HashMap<>();
            isGiftMap.put("value", detail.getIsGift());
            detailMap.put("mx_zp", isGiftMap);

            Map<String, Object> isLineTerminatedMap = new HashMap<>();
            isLineTerminatedMap.put("value", detail.getIsLineTerminated());
            detailMap.put("mx_zzh", isLineTerminatedMap);

            Map<String, Object> salesRepresentativeMap = new HashMap<>();
            salesRepresentativeMap.put("value", detail.getSalesRepresentative());
            detailMap.put("mx_xsywy", salesRepresentativeMap);

            Map<String, Object> productRequirementsNewMap = new HashMap<>();
            productRequirementsNewMap.put("value", detail.getProductRequirementsNew());
            detailMap.put("mx_cpmsx", productRequirementsNewMap);

            Map<String, Object> customerNameMap = new HashMap<>();
            customerNameMap.put("value", detail.getCustomerName());
            detailMap.put("mx_khmc", customerNameMap);

            Map<String, Object> salesOrderCodeMap = new HashMap<>();
            salesOrderCodeMap.put("value", detail.getSalesOrderCode());
            detailMap.put("mx_xsddh", salesOrderCodeMap);


            result.add(detailMap);

        }
        if ( purchaseOrder.getSaleOrderCode()!=null) {
            Header[] headers = ConnmeUtils.createHeaders();
            Map<String, Object> parameterDelete = new HashMap<>();
            parameterDelete.put("app_id", "6500165a60a971000ab0ad28");
            parameterDelete.put("entry_id", "65015e41ddd8340007a1698d");
            List<VvSaSaleOrder> documentnumber = PurchaseCommunity.queryBased(parameterDelete, headers, purchaseOrder.getSaleOrderCode(), "documentnumber", VvSaSaleOrder.class);
            if (documentnumber.size() > 0) {
                Map<String, Object> parameterInster = new HashMap<>();
                parameterInster.put("app_id", "6500165a60a971000ab0ad28");
                parameterInster.put("entry_id", "65015e41ddd8340007a1698d");
                parameterInster.put("data_id", documentnumber.get(0).get_id());
                for (int i = 0; i < documentnumber.get(0).getVvsasaleorderblist().size(); i++) {
                    for (PurchaseOrderDetail purchaseOrderDetail : purchaseOrder.getPurchaseOrderDetails()) {
                        if (purchaseOrderDetail.getProductCode().equals(documentnumber.get(0).getVvsasaleorderblist().get(i).getProductcode()) && purchaseOrderDetail.getSalesOrderCode().equals(documentnumber.get(0).getDocumentnumber())) {
                            documentnumber.get(0).getVvsasaleorderblist().get(i).setPurchaseorder(purchaseOrder.getCode());
                            break;
                        }
                    }
                }
                parameterInster.put("data", ConnmeUtils.convertEntityToMap(documentnumber));
                String jsonSale = JSONUtil.toJsonStr(parameterInster);
                ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSale);
            }
        }

        Map<String, Object> mx = new HashMap<>();
        mx.put("value", result);
        data.put("mx", mx);
        parameter.put("data", data);
        String jsonSale = JSONUtil.toJsonStr(parameter);
        JSONObject jdySale = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/create", originalHeaders, jsonSale);
        log.info("采购订单审核时：====" + jdySale);
    }

    @Override
    public String getMsgType() {
        return "PurchaseOrder_Audit";
    }


}
